<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator=">">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片区域 -->
    <el-card>
      <!-- 警示框 -->
      <el-alert title="注意: 只允许为第三等级分类设置相关参数"
                type="warning"
                show-icon
                :closable="false"></el-alert>

      <!-- 选择商品分类 -->
      <el-row class="cat_put">
        <el-form>
          <el-form-item label="请选择商品分类">
            <el-cascader expand-trigger="hover"
                         :options="parentParamsList"
                         :props="cascaderProps"
                         v-model="selectedKeys"
                         @change="handleChange">

            </el-cascader>
          </el-form-item>
        </el-form>
      </el-row>

      <!-- 标签页 -->
      <!-- v-model="activeName"  绑定name的值 -->
      <el-tabs v-model="activeName"
               @tab-click="handleTabClick">
        <el-tab-pane label="动态参数"
                     name="many">
          <el-button type="primary"
                     size="mini"
                     :disabled="isBtnDisabled"
                     @click="addParamsBtn">添加参数</el-button>
          <el-table :data="manyTableData"
                    border
                    stripe>
            <el-table-column type="expand">
              <template slot-scope="scope">
                <!-- 循环渲染tag标签 -->
                <el-tag :key="i"
                        v-for="(item,i) in (scope.row.attr_vals)"
                        closable
                        @close="handleClose(i,scope.row)">
                  {{item}}
                </el-tag>
                <el-input class="input-new-tag"
                          v-if="scope.row.inputVisible"
                          v-model="scope.row.inputValue"
                          ref="saveTagInput"
                          size="small"
                          @keyup.enter.native="handleInputConfirm(scope.row)"
                          @blur="handleInputConfirm(scope.row)">
                </el-input>
                <el-button v-else
                           class="button-new-tag"
                           size="small"
                           @click="showInput(scope.row)">+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index"
                             label="#"></el-table-column>
            <el-table-column label="属性名称"
                             prop="attr_name"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button size="mini"
                           type="primary"
                           icon="el-icon-edit"
                           @click="showEditDialog(scope.row.attr_id)">编辑</el-button>
                <el-button size="mini"
                           type="danger"
                           icon="el-icon-delete"
                           @click="delEditDialog(scope.row.attr_id)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>

        <el-tab-pane label="静态属性"
                     name="only">
          <el-button type="primary"
                     size="mini"
                     :disabled="isBtnDisabled"
                     @click="addParamsBtn">添加属性</el-button>
          <el-table :data="onlyTableData"
                    border
                    stripe>
            <el-table-column type="expand">
              <template slot-scope="scope">
                <!-- 循环渲染tag标签 -->
                <el-tag :key="i"
                        v-for="(item,i) in (scope.row.attr_vals)"
                        closable
                        @close="handleClose(i,scope.row)">
                  {{item}}
                </el-tag>
                <el-input class="input-new-tag"
                          v-if="scope.row.inputVisible"
                          v-model="scope.row.inputValue"
                          ref="saveTagInput"
                          size="small"
                          @keyup.enter.native="handleInputConfirm(scope.row)"
                          @blur="handleInputConfirm(scope.row)">
                </el-input>
                <el-button v-else
                           class="button-new-tag"
                           size="small"
                           @click="showInput(scope.row)">+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index"
                             label="#"></el-table-column>
            <el-table-column label="属性名称"
                             prop="attr_name"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button size="mini"
                           type="primary"
                           icon="el-icon-edit"
                           @click="showEditDialog(scope.row.attr_id)">编辑</el-button>
                <el-button size="mini"
                           type="danger"
                           icon="el-icon-delete"
                           @click="delEditDialog(scope.row.attr_id)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 添加对话框 -->
    <el-dialog :title="'添加' + titleText"
               :visible.sync="addDialogVisible"
               width="50%"
               @close="addDialogClose">
      <el-form :model="addParamsForm"
               :rules="addParamsFormRules"
               ref="addParamsFormRef">
        <el-form-item :label="titleText"
                      prop="attr_name">
          <el-input v-model="addParamsForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer"
            class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary"
                   @click="addParams">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 编辑对话框 -->
    <el-dialog :title="'编辑' + titleText"
               :visible.sync="editDialogVisible"
               width="50%"
               @close="editDialogClose">
      <el-form :model="editParamsForm"
               :rules="editParamsFormRules"
               ref="editParamsFormRef">
        <el-form-item :label="titleText"
                      prop="attr_name">
          <el-input v-model="editParamsForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer"
            class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary"
                   @click="editParams">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
// import LoginVue from '../Login.vue'
export default {
  data () {
    return {
      parentParamsList: [],
      cascaderProps: {
        // value 选中数据的值
        value: 'cat_id',
        // label 选中数据展示的值
        label: 'cat_name',
        children: 'children'
      },
      // 下拉选框的内容
      selectedKeys: [],
      // 动态或者静态的模式
      activeName: 'many',
      // 动态数据
      manyTableData: [],
      // 静态数据
      onlyTableData: [],
      // 控制添加框的显示与隐藏
      addDialogVisible: false,
      addParamsForm: {
        attr_name: ''
      },
      // 添加效验规则
      addParamsFormRules: {
        attr_name: [{ required: true, message: '请输入参数名称', trigger: 'blur' }]
      },
      // 控制修改框的显示与隐藏
      editDialogVisible: false,
      editParamsForm: {},
      // 修改效验规则
      editParamsFormRules: {
        attr_name: [{ required: true, message: '请输入参数名称', trigger: 'blur' }]
      }
    }
  },
  created () {
    this.getParamsList()
  },
  methods: {
    // 获取商品分类信息
    async getParamsList () {
      const { data: res } = await this.$http.get('categories')
      if (res.meta.status !== 200) {
        this.$message.error('获取商品分类信息失败')
      }
      //  console.log(res);
      this.parentParamsList = res.data
    },
    // 商品选择框的change事件
    handleChange () {
      this.getParamsData()
    },
    // Tab栏切换事件
    handleTabClick () {
      this.getParamsData()
    },
    // 获取所有的参数项列表
    async getParamsData () {
      if (this.selectedKeys.length !== 3) {
        this.selectedKeys = []
        //  this.$message.error('只允许为第三等级分类设置相关参数')
        this.manyTableData = []
        this.onlyTableData = []
        return
      }
      const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes`, { params: { sel: this.activeName } })
      if (res.meta.status !== 200) {
        this.$message.error('获取参数列表失败')
      }
      //  console.log(res.data);
      res.data.forEach(item => {
        //  console.log(item);
        item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
        //  console.log(item.attr_vals);
        // 文本框的显示与隐藏
        item.inputVisible = false
        // 文本框的内容
        item.inputValue = ''
      })
      if (this.activeName === 'many') {
        this.manyTableData = res.data
      } else {
        this.onlyTableData = res.data
      }
    },
    // 点击添加按钮时，添加对话框显示
    addParamsBtn () {
      this.addDialogVisible = true
    },
    // 点击添加对话框的确定，完成数据的添加
    addParams () {
      this.$refs.addParamsFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.post(`categories/${this.cateId}/attributes`, { attr_name: this.addParamsForm.attr_name, attr_sel: this.activeName })
        if (res.meta.status !== 201) {
          return this.$message.error('添加数据失败')
        }
        this.$message.success('添加数据成功')
        this.addDialogVisible = false
        this.getParamsData()
      })
    },
    // 关闭添加对话框时重置对话框的数据
    addDialogClose () {
      this.$refs.addParamsFormRef.resetFields()
    },
    // 获取数据用来更新
    async showEditDialog (attrId) {
      this.editDialogVisible = true
      //  console.log(attr_id);
      const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes/${attrId}`, { params: { attr_sel: this.activeName } })
      if (res.meta.status !== 200) {
        return this.$message.error('获取数据失败！')
      }
      this.editParamsForm = res.data
    },
    // 提交更新参数
    editParams () {
      this.$refs.editParamsFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.put(`categories/${this.cateId}/attributes/${this.editParamsForm.attr_id}`, { attr_name: this.editParamsForm.attr_name, attr_sel: this.activeName })
        if (res.meta.status !== 200) {
          return this.$message.error('更新数据失败！')
        }
        this.$message.success('更新数据成功！')
        this.getParamsData()
        this.editDialogVisible = false
      })
    },
    // 关闭编辑框时清空编辑框
    editDialogClose () {
      this.$refs.editParamsFormRef.resetFields()
    },
    // 删除按钮
    async delEditDialog (attrId) {
      const confirmResult = await this.$confirm(
        '此操作将永久删除该用户, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => err)
      if (confirmResult !== 'confirm') {
        return this.$message.info('删除已取消')
      }

      const { data: res } = await this.$http.delete(`categories/${this.cateId}/attributes/${attrId}`)
      // console.log(res);
      if (res.meta.status !== 200) {
        return this.$message.error('删除失败！')
      }
      this.$message.success('删除成功！')
      this.getParamsData()
    },
    // 当点击回车  或  失去焦点时触发事件
    async handleInputConfirm (row) {
      if (row.inputValue.trim().length === 0) {
        row.inputValue = ''
        row.inputVisible = false
        return
      }
      // 如果没有出错  后续处理
      row.attr_vals.push(row.inputValue.trim())
      row.inputValue = ''
      row.inputVisible = false
      const { data: res } = await this.$http.put(`categories/${this.cateId}/attributes/${row.attr_id}`, { attr_name: row.attr_name, attr_sel: row.attr_sel, attr_vals: row.attr_vals.join(' ') })
      if (res.meta.status !== 200) {
        return this.$message.error('添加商品信息失败！')
      }
      this.$message.success('添加商品信息成功！')
      //  this.getParamsData()
    },
    // 点击按钮时  输入框显示
    showInput (row) {
      row.inputVisible = true
      this.$nextTick(() => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    // 小标签关闭事件
    async handleClose (i, row) {
      row.attr_vals.splice(i, 1)
      const { data: res } = await this.$http.put(`categories/${this.cateId}/attributes/${row.attr_id}`, { attr_name: row.attr_name, attr_sel: row.attr_sel, attr_vals: row.attr_vals.join(' ') })
      if (res.meta.status !== 200) {
        return this.$message.error('添加商品信息失败！')
      }
      this.$message.success('添加商品信息成功！')
    }
  },
  computed: {
    // 按钮的禁用与开放
    isBtnDisabled () {
      if (this.selectedKeys.length !== 3) {
        return true
      }
      return false
    },
    cateId () {
      if (this.selectedKeys.length === 3) {
        return this.selectedKeys[2]
      }
      return null
    },
    titleText () {
      if (this.activeName === 'many') {
        return '动态参数'
      }
      return '静态属性'
    }
  }
}
</script>

<style lang="less" scoped>
.cat_put {
  margin: 15px 0;
}
.el-tag {
  margin: 10px;
}
.input-new-tag {
  width: 120px;
}
</style>
